/**
 * 
 */
package monster.comm.interceptor;

import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.session.RowBounds;

import monster.comm.dialect.Dialect;
import monster.comm.dialect.SQLServer2005Dialect;
import monster.comm.util.ReflectUtil;
import monster.comm.util.SysConstant;

/**
 * 分页拦截器基类 
 * 主要设置 数据库方言，分页sqlid,获得StatementHandler
 * @author wanghong
 * 2012-12-26
 * AbstractStatementHandlerInterceptor.java
 * 
 */
public abstract class AbstractStatementHandlerInterceptor implements Interceptor{
	protected String dialectClass=SysConstant.dialectClass;//sql serve方言
	protected String pageSqlId=SysConstant.pageSqlId;
	
	protected String getPageSqlId() {
		return pageSqlId;
	}

    protected void setPageSqlId(String pageSqlId) {
		this.pageSqlId = pageSqlId;
	}

	protected void setDialectClass(String dialectClass) throws Exception {  
        this.dialectClass = dialectClass; 
        Dialect dialect = (Dialect)Class.forName(this.dialectClass).newInstance();
        setDialect(dialect);
        
    }  
      
    protected Dialect dialect = new SQLServer2005Dialect();  
  
    protected void setDialect(Dialect dialect) {  
        this.dialect = dialect;  
    } 
  
    protected StatementHandler getStatementHandler(Invocation invocation) {  
        StatementHandler statement = (StatementHandler) invocation.getTarget();  
        if (statement instanceof RoutingStatementHandler) {  
            statement = (StatementHandler) ReflectUtil.getFieldValue(statement,  
                    "delegate");  
        }  
        return statement;  
    }  
    protected MappedStatement getMappedStatementHandler(StatementHandler statement) {  
    	MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(statement, "mappedStatement");
        return mappedStatement;  
    }   
    protected RowBounds getRowBounds(StatementHandler statement) {  
        return (RowBounds) ReflectUtil.getFieldValue(statement, "rowBounds");  
    }  
      
    protected boolean hasBounds(RowBounds rowBounds) {  
        return (rowBounds != null   
                && rowBounds.getLimit() > 0   
                && rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT);  
    }  
}
